import { useMouse } from "@vueuse/core";
import { Application, Container } from "pixi.js";
import { UserHub } from "../UserInput/UserListener";
const { x: MX, y: MY } = useMouse();
var supportTouch = "ontouchstart" in window;
export class MoveControl {
    constructor(public app: Application, public plane: Container) {
        if (!supportTouch) {
            app.view.addEventListener("mousedown", this.MoveStart);
            app.view.addEventListener("mousemove", this.MoveTo);
            app.view.addEventListener("mouseup", this.MoveEnd);
        } else {
            app.view.addEventListener("touchstart", this.MoveStart);
            app.view.addEventListener("touchmove", this.MoveTo);
            app.view.addEventListener("touchmove", this.MoveEnd);
        }
        UserHub.on("move", this.useMove);
        UserHub.on("stopMove", this.endMove);
    }
    destroy() {
        UserHub.off("move", this.useMove);
        UserHub.off("stopMove", this.endMove);
        const app = this.app;
        if (!supportTouch) {
            app.view.removeEventListener("mousedown", this.MoveStart);
            app.view.removeEventListener("mousemove", this.MoveTo);
            app.view.removeEventListener("mouseup", this.MoveEnd);
        } else {
            app.view.removeEventListener("touchstart", this.MoveStart);
            app.view.removeEventListener("touchmove", this.MoveTo);
            app.view.removeEventListener("touchmove", this.MoveEnd);
        }
    }

    useMove = () => {
        this.movable = true;
        this.plane.interactive = false;
    };
    endMove = () => {
        this.movable = false;
        this.plane.interactive = true;
    };

    private MouseOrigin = [0, 0];
    private planeOrigin = [0, 0];
    movable = false;
    private moving = false;
    MoveStart = (e: MouseEvent | TouchEvent) => {
        if (this.movable) {
            e.stopPropagation();
            e.preventDefault();
            this.moving = true;
            this.MouseOrigin = [MX.value, MY.value];
            const { x, y } = this.plane.position;
            this.planeOrigin = [x, y];
        }
    };
    MoveTo = (e: MouseEvent | TouchEvent) => {
        if (this.moving) {
            e.stopPropagation();
            e.preventDefault();
            if (this.movable && this.moving) {
                const [X, Y] = this.MouseOrigin;
                const x = this.planeOrigin[0] + MX.value - X;
                const y = this.planeOrigin[1] + MY.value - Y;
                this.plane.position.set(x, y);
            }
            UserHub.emit("moving");
        }
    };
    MoveEnd = (e: MouseEvent | TouchEvent) => {
        e.stopPropagation();
        e.preventDefault();
        this.moving = false;
    };
}
